<template>
  <el-dialog v-model="showDialog" title="修改用户" width="500px"
             :close-on-click-modal="false"
  >
    <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rulesType"
        label-width="80px"
        class="demo-ruleForm"
        status-icon
    >
      <el-form-item label="姓名" prop="name" style="max-width: 300px;width: 100%">
        <el-input v-model="ruleForm.name"/>
      </el-form-item>
      <el-form-item label="性别" prop="sex" style="max-width: 300px;width: 100%">
        <el-radio-group v-model="ruleForm.sex">
          <el-radio label="MALE" border>男</el-radio>
          <el-radio label="FEMALE" border>女</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="手机号" prop="phone" style="max-width: 300px;width: 100%">
        <el-input v-model="ruleForm.phone"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitEditForm(ruleFormRef)">
          修改
        </el-button>
      </el-form-item>

    </el-form>
  </el-dialog>
</template>

<script setup lang="ts">
import {onMounted, reactive, ref, defineExpose} from "vue";
import type {FormRules, FormInstance} from "element-plus";
import $api from "@/api";
import {ElNotification} from "element-plus";

const showDialog = ref(false)
const dialogModel = ref('create')


const createLoading = ref(false)
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive({
  id: null,
  sex: 'MALE',
  name: '',
  phone: '',
})
const rulesType = reactive<FormRules>({
  name: [
    {required: true, message: '请输入姓名', trigger: 'blur'},
    {min: 1, max: 6, message: '长度限制在 1 ~ 6 个字符', trigger: 'blur'},
  ],
  sex: [
    {required: true, message: '请选择性别', trigger: 'blur'},
  ],
})
const emit = defineEmits(['edited'])

const submitEditForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (createLoading.value) {
        return
      }
      createLoading.value = true
      $api.userApi.editFrontUser(ruleForm).then(res => {
        createLoading.value = false
        ElNotification({
          title: '成功',
          message: '修改用户信息成功！',
          type: 'success',
        })
        emit('edited')
      }).catch(() => {
        createLoading.value = false
      })
    } else {

    }
  })
}
const edit = (row: any) => {
  showDialog.value = true
  ruleForm.id = row.id
  ruleForm.name = row.name
  ruleForm.phone = row.phone
  ruleForm.sex = row.sex
}
// 将这个方法暴露出去,这样父组件就可以使用了哈
defineExpose({
  showDialog,
  edit
})
</script>

<style scoped>

</style>